package com.example.eddie.test.activity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.eddie.test.ConnectionWeb.Connection;
import com.example.eddie.test.MyAdapter.InfoAdapter;
import com.example.eddie.test.MyDatabases.MyDatabaseHelper;
import com.example.eddie.test.PoJo.BuildValue;
import com.example.eddie.test.PoJo.TeacherClassInfo;
import com.example.eddie.test.R;
import com.example.eddie.test.Util.JsoupHtmlUtil;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;

public class GetBuildActivity extends AppCompatActivity {

    private SQLiteDatabase writableDatabase;
    private MyDatabaseHelper database;
    private String SessionId;
    private ImageView view;
    private MaterialEditText verification;

    private ArrayAdapter BuildAdapter;

    private List<String> ClassRoomID = new ArrayList<>();
    private ArrayAdapter ClassRoomAdapter;

    private String ID;
    private String value;
    private List<TeacherClassInfo> list = new ArrayList<>();

    private JsoupHtmlUtil util;
    private InfoAdapter infoAdapter;

    private LinearLayout yzm_linear;

    private static final String[] DAY = new String[]{"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
    private static final String[] TIME = new String[]{"第一节", "第二节", "第三节", "第四节"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_build);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        updateBuild();
        init();
        getImg();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void init() {
        util = new JsoupHtmlUtil();
        database = new MyDatabaseHelper(this, "SearchInfo.db", null, 1);
        writableDatabase = database.getWritableDatabase();

        view = (ImageView) findViewById(R.id.yzm_view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getImg();
            }
        });

        verification = (MaterialEditText) findViewById(R.id.verification);

        List<String> ClassRoomList = new ArrayList<>();
        final Spinner class_room = (Spinner) findViewById(R.id.class_room);
        ClassRoomAdapter = new ArrayAdapter<>(this,R.layout.support_simple_spinner_dropdown_item,ClassRoomList);
        class_room.setAdapter(ClassRoomAdapter);
        class_room.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                ID = ClassRoomID.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        yzm_linear = (LinearLayout) findViewById(R.id.yzm_linear);

        ListView spinner = (ListView) findViewById(R.id.view_Info);
        infoAdapter = new InfoAdapter(this,R.layout.teacher_layout,list);
        spinner.setAdapter(infoAdapter);

        List<String> BuildList = new ArrayList<>();
        final Spinner build = (Spinner) findViewById(R.id.build);
        BuildAdapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, BuildList);
        build.setAdapter(BuildAdapter);
        build.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String name = build.getSelectedItem().toString();
                getBuildRoom(name);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //更新数据库数据
    public void updateBuild() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Document document = Jsoup.connect("http://59.79.112.9/ZNPK/Private/List_JXL.aspx?id=1").timeout(3000).get();
                    String HtmlBuildInfo = document.toString().split("'")[1];
                    Document options = Jsoup.parse(HtmlBuildInfo);
                    Elements option = options.select("option");

                    List<String> buildListName = getBuildListName();
                    for (Element opt : option) {
                        String text = opt.text();
                        String vlaue = opt.attr("value");
                        if (!buildListName.contains(text)) {
                            if (!text.equals("")) {
                                ContentValues values = new ContentValues();
                                values.put("name", text);
                                values.put("number", vlaue);

                                writableDatabase.insert("BuildInfo", null, values);
                                values.clear();
                            }
                        }
                    }

                    initBuildAdapter();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //初始化建筑spinner的adapter数据
    private void initBuildAdapter() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                List<String> list = getBuildListName();
                BuildAdapter.clear();
                BuildAdapter.addAll(list);
                BuildAdapter.notifyDataSetChanged();
            }
        });
    }

    //读取数据库数据，初始化list
    private List<String> getBuildListName() {
        List<String> list = new ArrayList<>();
        Cursor cursor = writableDatabase.query("BuildInfo", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                String name = cursor.getString(cursor.getColumnIndex("name"));
                list.add(name);
            } while (cursor.moveToNext());
        }
        return list;
    }


    private void getBuildRoom(String name) {
        Cursor cursor = writableDatabase.query("BuildInfo", null, "name like ?", new String[]{name}, null, null, null);
        if (cursor.getCount() != 0) {
            cursor.moveToFirst();
            value = cursor.getString(2);
            initBuildRoomAdapterList(value);
        } else {
            Toast.makeText(this, "抱歉哦！出了一点错误~", Toast.LENGTH_SHORT).show();
        }
    }

    private void initBuildRoomAdapterList(final String value) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Document document = null;
                try {
                    ClassRoomID.clear();
                    document = Jsoup.connect("http://59.79.112.9/ZNPK/Private/List_ROOM.aspx?w=150&id=" + value).timeout(3000).get();
                    String HtmlBuildRoomInfo = document.toString().split("'")[1];
                    Document options = Jsoup.parse(HtmlBuildRoomInfo);
                    Elements option = options.select("option");

                    List<String> list = new ArrayList<>();

                    for (Element opt : option) {
                        String text = opt.text();
                        String vlaue = opt.attr("value");
                        list.add(text);
                        ClassRoomID.add(vlaue);
                        Log.i("xxxzzz",vlaue);
                    }

                    initBuildRoomAdapter(list);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    private void initBuildRoomAdapter(final List<String> list) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ClassRoomAdapter.clear();
                ClassRoomAdapter.addAll(list);
                ClassRoomAdapter.notifyDataSetChanged();
            }
        });
    }


    public void get(View view) {
        getDataInfo();
    }

    private void getDataInfo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String yzm = verification.getText().toString();
                try {
                    URL url = new URL("http://59.79.112.9/ZNPK/KBFB_RoomSel_rpt.aspx");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setDoOutput(true);
                    connection.addRequestProperty("Referer","http://59.79.112.9/ZNPK/KBFB_RoomSel.aspx");
                    connection.addRequestProperty("Cookie",SessionId);

                    OutputStream outputStream = connection.getOutputStream();
                    String post = "Sel_XNXQ=20170&rad_gs=1&txt_yzm=" + yzm + "&Sel_XQ=1&Sel_JXL="+value+"&Sel_ROOM="+ID;
                    outputStream.write(post.getBytes());
                    outputStream.flush();
                    outputStream.close();

                    InputStream inputStream = connection.getInputStream();
                    BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream,"GB2312"));
                    String line = null;
                    StringBuilder sBuilder = new StringBuilder();
                    while ((line = bf.readLine())!=null){
                        sBuilder.append(line);
                    }

                    JsoupData(sBuilder.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    private void JsoupData(String HtmlData){
        String td = Jsoup.parse(HtmlData).select("td").text();

        if (HtmlData.contains("验证码错误！")){
            showToast("Wops~ 验证码错误!");
            resetListView();
            getImg();
        }else if (td.equals("")){
            showToast("Wops~ 这个教室没有课哦～");
            resetListView();
            getImg();
        }else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    yzm_linear.setVisibility(View.GONE);
                }
            });

            FormatDate(HtmlData);
        }
    }

    private void showToast(final String text){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                yzm_linear.setVisibility(View.VISIBLE);
            }
        });
    };

    private void resetListView(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                list.clear();
                infoAdapter.notifyDataSetChanged();
            }
        });
    }

    private void FormatDate(String html) {
        String[][] table = util.jsoup(html);

        String thisTime1;
        String thisTime2;
        TeacherClassInfo teacherClassInfo = null;

        for (int x = 0; x < table.length; x++) {
            for (int y = 0; y < table[x].length; y++) {
                teacherClassInfo = null;
                String s = table[x][y];
                if (!s.equals("")) {
                    String data = DAY[y];
                    if (x <= 2) {
                        thisTime1 = "上午";
                        thisTime2 = TIME[x];
                    } else {
                        thisTime1 = "下午";
                        thisTime2 = TIME[x];
                    }
                    teacherClassInfo = new TeacherClassInfo(s, thisTime1, thisTime2, data,y);
                }
                if (teacherClassInfo!=null) {
                    list.add(teacherClassInfo);
                }

                sort();
            }
        }
    }

    private void sort(){
        util.sort(list);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                infoAdapter.notifyDataSetChanged();
            }
        });
    }

    private void getImg() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://59.79.112.9/sys/ValidateCode.aspx");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.addRequestProperty("Referer", "http://59.79.112.9/ZNPK/KBFB_RoomSel.aspx");

                    InputStream is = connection.getInputStream();
                    final Bitmap bitmap = BitmapFactory.decodeStream(is);
                    String headerField = connection.getHeaderField("set-cookie");
                    SessionId = headerField.split(";")[0];
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            view.setImageBitmap(bitmap);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
